package com.waa.gulimall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {

    /**
     * 使用json序列化机制，进行消息转换
     *
     * @return
     */
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Bean
    public Exchange orderEventExchange() {
        return ExchangeBuilder.topicExchange("order-event-exchange").durable(true).build();
    }

    @Bean
    public Queue orderReleaseOrderQueue() {
        return QueueBuilder.durable("order.release.order.queue").build();
    }

    @Bean
    public Queue orderDelayQueue() {
        Map<String, Object> args = new HashMap<>(3);
        //声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", "order-event-exchange");
        //声明当前队列的死信路由 key
        args.put("x-dead-letter-routing-key", "order.release.order");
        //声明队列的 TTL
        args.put("x-message-ttl", 120000);
        return QueueBuilder.durable("order.delay.queue").withArguments(args).build();
    }

    @Bean
    public Binding stockReleaseBinding(@Qualifier("orderReleaseOrderQueue") Queue orderReleaseOrderQueue,
                                       @Qualifier("orderEventExchange") Exchange orderEventExchange) {
        return BindingBuilder.bind(orderReleaseOrderQueue).to(orderEventExchange).with("order.release.order").noargs();
    }

    @Bean
    public Binding stockLockedBinding(@Qualifier("orderDelayQueue") Queue orderDelayQueue,
                                      @Qualifier("orderEventExchange") Exchange orderEventExchange) {
        return BindingBuilder.bind(orderDelayQueue).to(orderEventExchange).with("order.create.order").noargs();
    }

    /**
     * 订单释放和库存释放进行绑定
     */
    @Bean
    public Binding orderReleaseOtherBinding() {
        return new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE, "order-event-exchange"
                , "order.release.other.#", null);
    }

    @Bean
    public Queue orderSeckillOrderQueue() {
        return new Queue("order.seckill.order.queue", true, false, false);
    }

    @Bean
    public Binding orderSeckillOrderQueueBinding(
            @Qualifier("orderSeckillOrderQueue") Queue orderSeckillOrderQueue,
            @Qualifier("orderEventExchange") Exchange orderEventExchange
    ) {

        return BindingBuilder.bind(orderEventExchange).to(orderEventExchange).with("order.seckill.oreder").noargs();
    }
}
